<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Bid_m extends MY_Model {

	public function __construct()
	{
		parent::__construct();
		$this->load->library('module_helper');
		
	}

	function bidding(){
		$total = count( $this->db->select("TBLBID.*")->
						from(TBL_BID." AS TBLBID")->
						join(TBL_SHOW." AS TBLSHOW","TBLBID.show_ref_no=TBLSHOW.ref_no")->
						where("TBLSHOW.status",'opening')->
						get()->result() 
					);
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : 25;
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		$partial = array();
		foreach($_GET as $key=> $value){
			if($key != "per_page")
				$partial["$key"] = "$key=$value";
		}
		
		$pagination = create_pagination( 
								$uri = 'admin/dataman/bid/bidding/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
	 	$records = $this->db->select("TBLBID.*")->
						from(TBL_BID." AS TBLBID")->
						join(TBL_SHOW." AS TBLSHOW","TBLBID.show_ref_no=TBLSHOW.ref_no")->
						where("TBLSHOW.status",'opening')->
						order_by('id','desc')->
						limit($records_per_page, $per_page )->
						get()->result() ; 
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	function processing(){
		$total = count( $this->db-> 
						where( "status LIKE 'closed' AND pay_status IS NULL" )->
						get(TBL_SHOW)->result() 
					);
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : 25;
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		$partial = array();
		foreach($_GET as $key=> $value){
			if($key != "per_page")
				$partial["$key"] = "$key=$value";
		}
		
		$pagination = create_pagination( 
								$uri = 'admin/dataman/bid/processing/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
	 	$records = $this->db->where( "status LIKE 'closed' AND pay_status IS NULL" )->
						order_by('id','desc')->
						limit($records_per_page, $per_page )->
						get(TBL_SHOW)->result() ; 
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	function completed(){
		$total = count( $this->db-> 
						where( "status LIKE 'closed' AND pay_status IS NOT NULL" )->
						get(TBL_SHOW)->result() 
					);
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : 25;
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		$partial = array();
		foreach($_GET as $key=> $value){
			if($key != "per_page")
				$partial["$key"] = "$key=$value";
		}
		
		$pagination = create_pagination( 
								$uri = 'admin/dataman/bid/completed/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
	 	$records = $this->db->where( "status LIKE 'closed' AND pay_status IS NOT NULL" )->
						order_by('id','desc')->
						limit($records_per_page, $per_page )->
						get(TBL_SHOW)->result() ; 
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	function search(){
		$s = ($_GET['key']);
		$filter = ($_GET['filter']);
		$options = array('id'=>'Bid ref','ref_no'=>'Show ref','show_name'=>'Show name','artist'=>'Artist', 'buyer_acc_code'=>'Buyer Account Code', 'seller_acc_code'=>"Seller Account Code");
		if(!in_array($filter, array_keys($options))){
			$filter = 'id';
		}
		switch($filter){
			case 'id':
				$condition = "TBLBID.id =".intval($s);
				break;
			case 'ref_no':
				$condition = "TBLBID.show_ref_no ='$s'";
				break;
			case 'show_name':
				$condition = "TBLSHOW.name LIKE '$s%'";
				break;
			case 'artist':
				$condition = "TBLSHOW.artist LIKE '$s%'";
				break;	
			case 'buyer_acc_code':
				$condition = "TBLBID.account_code ='$s'";
				break;
			case 'seller_acc_code':
				$condition = "TBLSHOW.user_created_id LIKE '$s'";
				break;	
		}
		
		$total = count( $this->db->select("TBLBID.*")->
						from(TBL_BID." AS TBLBID")->
						join(TBL_SHOW." AS TBLSHOW","TBLBID.show_ref_no=TBLSHOW.ref_no")->
						where( $condition )->
						get()->result()
					);
		$records_per_page = isset($_GET['records_per_page']) ? intval($_GET['records_per_page']) : 25;
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 0;
		
		$partial = array();
		foreach($_GET as $key=> $value){
			if($key != "per_page")
				$partial["$key"] = "$key=$value";
		}
		
		$pagination = create_pagination( 
								$uri = 'admin/dataman/bid/search/?'.implode('&',$partial), 
								$total_rows = $total , 
								$limit= $records_per_page,
								$uri_segment = 0,
								TRUE, TRUE 
							);
	 	$records = $this->db->select("TBLBID.*")->
						from(TBL_BID." AS TBLBID")->
						join(TBL_SHOW." AS TBLSHOW","TBLBID.show_ref_no=TBLSHOW.ref_no")->
						where( $condition )->
						order_by('id','desc')->
						limit($records_per_page, $per_page )->
						get()->result() ; 
		return array('pagination'=> $pagination, 'items'=>$records, 'total_records'=>$total);
	}
	
	function change_pay_status(){
		$SHOW = $this->show_entity->init('id', $_POST['show_id']);
		$SHOW->setPayStatus( $_POST['status']== '' ? NULL : $_POST['status'] );
		$SHOW->update();
		$this->session->set_flashdata('success', lang('dataman.success'));
		exit();
	}
	
	function email(){
		$SHOW = $this->show_entity->init('id', intval($_GET['show_id']));
		$BID = $this->bid_entity->init('id', intval($_GET['bid_id']));
		
		return $this->db->where(array('show_id'=>$SHOW->getId(), 'bid_id'=>$BID->getId()))->get(TBL_EMAIL_ADMIN)->result();
	}
	
	function submit_email_compose(){
		$record = $this->db->where('id', $_POST['item_id'])->get(TBL_EMAIL_ADMIN)->result();
		switch($_POST['action']){
			case 'cancel_email':
				break;
			case 'delete_email':	
				$this->db->where('id',$record[0]->id)->delete(TBL_EMAIL_ADMIN);
				break;
			case 'send_email':
				$this->load->library('email_sender');
				$this->db->where('id',$record[0]->id)->update(TBL_EMAIL_ADMIN, array('body'=>$_POST['body'], 'status'=>'sent','sent_date'=>time()));
				$record = $this->db->where('id', $_POST['item_id'])->get(TBL_EMAIL_ADMIN)->result();
				$this->email_sender->setFromEmail($record[0]->email_from);
				$this->email_sender->setToEmail($record[0]->email_to);
				$this->email_sender->setSubject($record[0]->subject);
				$this->email_sender->setBody($record[0]->body);
				$this->email_sender->sendEmail();
				
				if($record[0]->email_slug == "notify-seller-escrow-receipt"){
					$this->crontab_email->cronUpdate( "NOTIFYSELLER_ESCROWRELEASE",'_sendEmailToSeller_escrowReleaseNotify', $record[0]->show_id.",".$record[0]->bid_id, array(workingDaysTimeStamp(3)) );	
				}
				break;
		}
		$this->session->set_flashdata('success', lang('dataman.success'));
		exit();
	}
	
	function compose(){
		$SHOW = $this->show_entity->init('id', intval($_GET['show_id']));
		$BID = $this->bid_entity->init('id', intval($_GET['bid_id']));
		$BUYER = clone_ ( $this->user_entity->init('acc_code', $BID->getAccountCode()) );
		$SELLER = clone_ ( $this->user_entity->init('id', $SHOW->getUserCreatedId()) );
		$template = $this->module_helper->getTemplateMail( $_GET['slug'] );
		
		if(!$SHOW || !$BID || empty($template)){
			show_404();exit();
		}	
		 
		$record_available = $this->db->where(array('show_id'=>$SHOW->getId(), 'bid_id'=>$BID->getId(), 'email_slug'=>$template['slug'] ))->get(TBL_EMAIL_ADMIN)->result();
		 
		if(empty($record_available)){
			$email_from = Settings_class::get('server_email');
			switch($_GET['slug']){
				case 'notify-seller-escrow-receipt':
					$orgArr = array("{###SHOW_REF###}" ,"{###SHOW###}", "{###BUYER_DETAILS###}");
					$ref_link = "<a href='".site_url('seller/show_details/'.$SHOW->getRefNo())."'>".$SHOW->getRefNo()."</a>";
					$content  = "<table>";
					$content .= "<tr><td>Email</td> <td>".$BUYER->getEmail()."</td></tr>";
					$content .= "<tr><td>First name</td> <td>".$BUYER->getFirstName()."</td></tr>";
					$content .= "<tr><td>Last name</td> <td>".$BUYER->getLastName()."</td></tr>";
					$content .= "<tr><td>Job title</td> <td>".$BUYER->getJobTitle()."</td></tr>";
					$content .= "<tr><td>Company/Organization</td> <td>".$BUYER->getCompany()."</td></tr>";
					$content .= "<tr><td>Company Website</td> <td>".$BUYER->getCompanyUrl()."</td></tr>";
					$content .= "<tr><td>Company Profile</td> <td>".$BUYER->getCompanyProfile()."</td></tr>";
					$content .= "<tr><td>Country</td> <td>".$BUYER->getCountry()."</td></tr>";
					$content .= "<tr><td>Address Line 1</td> <td>".$BUYER->getAddressLine1()."</td></tr>";
					$content .= "<tr><td>Address Line 2</td> <td>".$BUYER->getAddressLine2()."</td></tr>";
					$content .= "<tr><td>City</td> <td>".$BUYER->getCity()."</td></tr>";
					$content .= "<tr><td>State</td> <td>".$BUYER->getState()."</td></tr>";
					$content .= "<tr><td>Zip</td> <td>".$BUYER->getZip()."</td></tr>";
					$content .= "<tr><td>Workphone</td> <td>".$BUYER->getWorkPhone()."</td></tr>";
					$content .= "<tr><td>Mobile</td> <td>".$BUYER->getMobile()."</td></tr>";
					
					if(($BUYER->getShowType())){
						$array = showTypeDataConfig(); 
						$array2 = array();
						foreach(explode(',',$BUYER->getShowType()) as $element){
							$array2[] = $array[$element];
						}
						$showType= implode(', ',$array2);
					}else{
						$showType= "";
					}	
					$content .= "<tr><td>Show Type</td> <td>".$showType."</td></tr>";
					
					if(($BUYER->getCountryOrigin())){
						$array = countryOriginDataConfig(); 
						$array2 = array();
						foreach(explode(',',$BUYER->getCountryOrigin()) as $element){
							$array2[] = $array[$element];
						}
						$countryOrigin=  implode(', ',$array2);
					}else{
						$countryOrigin= "";
					}		
					$content .= "<tr><td>Country of Origin</td> <td>".$countryOrigin."</td></tr>";
					
					if(($BUYER->getMusicGenre())){
						$array = musicGenreDataConfig(); 
						$array2 = array();
						foreach(explode(',',$BUYER->getMusicGenre()) as $element){
							$array2[] = $array[$element];
						}
						$musicGenre = implode(', ',$array2);
					}else{
						$musicGenre = "";
					}	
					$content .= "<tr><td>Music Genre</td> <td>".$musicGenre."</td></tr>";
					$content .= "</table>";
					
					$rplArr = array( $ref_link ,$SHOW->getName(), $content );
					$body = ( str_replace( $orgArr , $rplArr , $template['body'] ) );
					$this->db->insert(TBL_EMAIL_ADMIN , 
										array('show_id'=>$SHOW->getId(), 'bid_id'=>$BID->getId(), 'status'=>'pending',
												'email_slug'=>$template['slug'], 'email_from'=>$email_from,
												'email_to'=>$SELLER->getEmail(),'subject'=>$template['subject'],
												'body'=>$body
										)
									);
					break;	
				case 'confirm-seller-buyer-bank-fund-net-fee-release':
					$orgArr = array("{###SHOW_REF###}" ,"{###SHOW###}", "{###BID_DUE_DATE###}");
					$ref_link = "<a href='".site_url('seller/show_details/'.$SHOW->getRefNo())."'>".$SHOW->getRefNo()."</a>";
					$rplArr = array( $ref_link , $SHOW->getName(), sbxDateFormat($SHOW->getBidDueDate()) );
					$body = ( str_replace( $orgArr , $rplArr , $template['body'] ) );
					$this->db->insert(TBL_EMAIL_ADMIN , 
										array('show_id'=>$SHOW->getId(), 'bid_id'=>$BID->getId(), 'status'=>'pending',
												'email_slug'=>$template['slug'], 'email_from'=>$email_from,
												'email_to'=>$SELLER->getEmail(),'subject'=>$template['subject'],
												'body'=>$body
										)
									);
					break;	
				case 'seller-buyer-file-dispute-fund-net-fee-release':	
					$orgArr = array( "{###BUYER_ACC_CODE###}" ,"{###SHOW_LINK###}" );
					$ref_link = "<a href='".site_url('seller/show_details/'.$SHOW->getRefNo())."'>".$SHOW->getName()."</a>";
					$rplArr = array( $BUYER->getAccCode(), $ref_link  );
					$body = ( str_replace( $orgArr , $rplArr , $template['body'] ) );
					$this->db->insert(TBL_EMAIL_ADMIN , 
										array('show_id'=>$SHOW->getId(), 'bid_id'=>$BID->getId(), 'status'=>'pending',
												'email_slug'=>$template['slug'], 'email_from'=>$email_from,
												'email_to'=>$SELLER->getEmail(),'subject'=>$template['subject'],
												'body'=>$body
										)
									);
					break;	
				case 'notify-seller-escrow-second-receipt':	
					$orgArr = array( "{###SHOW_REF###}" ,"{###SHOW###}" );
					$ref_link = "<a href='".site_url('seller/show_details/'.$SHOW->getRefNo())."'>".$SHOW->getRefNo()."</a>";
					$rplArr = array( $ref_link , $SHOW->getName() );
					$body = ( str_replace( $orgArr , $rplArr , $template['body'] ) );
					$this->db->insert(TBL_EMAIL_ADMIN , 
										array('show_id'=>$SHOW->getId(), 'bid_id'=>$BID->getId(), 'status'=>'pending',
												'email_slug'=>$template['slug'], 'email_from'=>$email_from,
												'email_to'=>$SELLER->getEmail(),'subject'=>$template['subject'],
												'body'=>$body
											)
									);
					break;	
				case 'one-day-b4-dispute-confirm-buyer-fund-release':	
					$orgArr = array( "{###SHOW_REF###}" ,"{###SHOW###}" ,"{###BID_DUE_DATE###}");
					$show_link = "<a href='".site_url('buyer/shows/view/'.$SHOW->getRefNo())."'>".$SHOW->getRefNo()."</a>";
					$rplArr = array( $show_link , $SHOW->getName(), sbxDateFormat($SHOW->getBidDueDate()) );
					$body = ( str_replace( $orgArr , $rplArr , $template['body'] ) );
					$this->db->insert(TBL_EMAIL_ADMIN , 
										array('show_id'=>$SHOW->getId(), 'bid_id'=>$BID->getId(), 'status'=>'pending',
												'email_slug'=>$template['slug'], 'email_from'=>$email_from,
												'email_to'=>$BUYER->getEmail(),'subject'=>$template['subject'],
												'body'=>$body
											)
									);
					break;	
				case 'buyer-file-dispute-notify-send-fund-to-buyer':
					$orgArr = array( "{###SHOW_REF###}" ,"{###SHOW###}" );
					$show_link = "<a href='".site_url('buyer/shows/view/'.$SHOW->getRefNo())."'>".$SHOW->getRefNo()."</a>";
					$rplArr = array( $show_link , $SHOW->getName() );
					$body = ( str_replace( $orgArr , $rplArr , $template['body'] ) );
					$this->db->insert(TBL_EMAIL_ADMIN , 
										array('show_id'=>$SHOW->getId(), 'bid_id'=>$BID->getId(), 'status'=>'pending',
												'email_slug'=>$template['slug'], 'email_from'=>$email_from,
												'email_to'=>$BUYER->getEmail(),'subject'=>$template['subject'],
												'body'=>$body
											)
									);
					break;	
				case 'seller-dispute-file-notify-buyer-advise-fund':
					$body =  $template['body'] ;
					$this->db->insert(TBL_EMAIL_ADMIN , 
										array('show_id'=>$SHOW->getId(), 'bid_id'=>$BID->getId(), 'status'=>'pending',
												'email_slug'=>$template['slug'], 'email_from'=>$email_from,
												'email_to'=>$BUYER->getEmail(),'subject'=>$template['subject'],
												'body'=>$body
											)
									);
					break;	
				case 'notify-seller-bid-closed-ready-award-selection':
					$orgArr = array( "{###SHOW_REF###}" ,"{###SHOW###}", "{###BID_DUE_DATE###}" );
					$ref_link = "<a href='".site_url('seller/show_details/'.$SHOW->getRefNo())."'>".$SHOW->getRefNo()."</a>";
					$rplArr = array( $ref_link , $SHOW->getName(), sbxDateFormat($SHOW->getBidDueDate()) );
					$body = ( str_replace( $orgArr , $rplArr , $template['body'] ) );
					$this->db->insert(TBL_EMAIL_ADMIN , 
										array('show_id'=>$SHOW->getId(), 'bid_id'=>$BID->getId(), 'status'=>'pending',
												'email_slug'=>$template['slug'], 'email_from'=>$email_from,
												'email_to'=>$SELLER->getEmail(),'subject'=>$template['subject'],
												'body'=>$body
											)
									);
					break;	
			}
			 
			return $this->db->where( array('show_id'=>$SHOW->getId(), 'bid_id'=>$BID->getId(), 'email_slug'=>$template['slug'] ))->get(TBL_EMAIL_ADMIN)->result();
			 
		}else{
			return $record_available;
		}
	
	}
	
	
	
	
}
